package com.neo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class RandomUserNameUtil {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public String getRandomUserName() throws Exception{
		
		List<Character> list = new ArrayList<Character>();
		for(char c = 'a'; c <= 'z'; c++){
			list.add(c);
		}
		String enStr = ""; 
		String numStr = "";
		
		for(int i = 0; i < 2; i++){
			int num = (int)(Math.random() * 26);
			enStr = enStr + list.get(num);
		}
		
		for(int i = 0; i < 6; i++){
			numStr += (int)(Math.random() * 10);
		}
		
		String userName = "djs" + numStr + enStr;
		
		while(!isUserExist((userName))){
			userName = getRandomUserName();
		}
		return "djs" + numStr + enStr;
	}
	
	private boolean isUserExist(String userName) throws Exception{
		
		boolean result = true;
		
		if(userName == null){
			result = false;
			return result;
		}
		
		StringBuffer querySql = new StringBuffer();
		querySql.append("SELECT USERNAME FROM inv_user WHERE USERNAME = '" + userName +"' OR MOBILE = '" + userName +"'");
		querySql.append(" UNION ");
		querySql.append(" SELECT USERNAME FROM inv_user_account WHERE USERNAME = '" + userName + "'");
		try{
			
			List<Map<String,Object>> userNames = jdbcTemplate.queryForList(querySql.toString(), new Object[]{});
			if(userNames != null && userNames.size() > 0){
				result = false;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		return result;
	}
}
